<template>
  <div style="width: 100%; height: 100%">
    <h1>企业信息管理</h1>
    <!-- 查询框 -->
    <div>
      <el-tag>企业信息管理</el-tag>
      <el-input v-model="keyword" style="width: 300px; margin-left: 10px; margin-right: 10px" placeholder="请输入关键词"></el-input>
      <el-button type="primary" @click="fetchCompanies">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>



    <!-- 企业列表 -->
    <!-- 表格 -->
    <div style="margin: 10px 0">
      <el-table :data="companies" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="company_id" label="公司ID" width="100" align="center"></el-table-column>
        <el-table-column prop="company_name" label="公司名称"></el-table-column>
        <el-table-column prop="industry" label="行业"></el-table-column>
        <el-table-column prop="website" label="网站"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column prop="contact_person" label="联系人"></el-table-column>
        <el-table-column prop="contact_email" label="联系邮箱"></el-table-column>
        <el-table-column prop="contact_phone" label="联系电话"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(scope.row.company_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑企业信息模态框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="editItem" label-width="100px" :rules="rule">
        <el-form-item label="公司名称">
          <el-input v-model="editItem.company_name"></el-input>
        </el-form-item>
        <el-form-item label="行业">
          <el-input v-model="editItem.industry"></el-input>
        </el-form-item>
        <el-form-item label="网站">
          <el-input v-model="editItem.website"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editItem.description"></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="editItem.contact_person"></el-input>
        </el-form-item>
        <el-form-item label="联系邮箱">
          <el-input v-model="editItem.contact_email"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editItem.contact_phone"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="editItem.address"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">{{ isEditing ? '保存' : '新增' }}</el-button>
      </div>
    </el-dialog>

    <!-- 选项卡 -->
    <el-tabs v-model="activeTab">
      <!-- 企业信息选项卡 -->
      <el-tab-pane label="企业信息" name="EnterpriseInformationManagement">
        <el-form :model="currentCompany" label-width="220px">
          <el-form-item  label="公司名称">
            <el-input v-model="currentCompany.company_name" />
          </el-form-item>
          <el-form-item label="所属行业">
            <el-input v-model="currentCompany.industry" />
          </el-form-item>
          <el-form-item label="公司网站">
            <el-input v-model="currentCompany.website" />
          </el-form-item>
          <el-form-item label="公司简介">
            <el-input type="textarea" v-model="currentCompany.description" />
          </el-form-item>
          <el-form-item label="联系人">
            <el-input v-model="currentCompany.contact_person" />
          </el-form-item>
          <el-form-item label="联系邮箱">
            <el-input v-model="currentCompany.contact_email" />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="currentCompany.contact_phone" />
          </el-form-item>
          <el-form-item label="公司地址">
            <el-input v-model="currentCompany.address" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" native-type="submit" @click="updateEnterpriseInfo">更新企业信息</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>

</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      activeTab: 'EnterpriseInformationManagement', // 默认选中的选项卡
      currentCompany: {}, // 当前公司信息
      certificationInfo: [], // 认证信息
      enterpriseInfo:{},
      industries: [], // 行业列表
      user:JSON.parse(localStorage.getItem('userData')) || {},

//__________
      keyword: '', // 查询关键词
      companies: [], // 企业信息列表
      currentPage: 1, // 当前页数
      pageSize: 5, // 每页显示的条数
      totalItems: 0, // 总条数
      dialogVisible: false, // 企业信息模态框可见性
      editItem: { // 编辑/新增的数据
        company_id: '',
        company_name: '',
        industry: '',
        website: '',
        description: '',
        contact_person: '',
        contact_email: '',
        contact_phone: '',
        address: ''
      },
      isEditing: false, // 是否为编辑模式
      rule: {
        company_name: [
          {required: true, message: '请输入公司名称', trigger: 'blur'}
        ]
      }
    };
  },

  computed: {
    dialogTitle() {
      return this.isEditing ? '编辑企业信息' : '新增企业信息';
    }
  },

  mounted() {
    this.fetchCompanies();
    //________________
// 初始化数据
    this.enterpriseInfo = {
      company_name: '',
      industry: '',
      website: '',
      description: '',
      contact_person: '',
      contact_email: '',
      contact_phone: '',
      address: ''
    };
    // this.fetchCertificationInfo(); // 获取认证信息
    // this.fetchIndustries(); // 获取行业列表
    // 获取行业列表
    // this.fetchIndustries();
    // 获取当前公司信息
    this.fetchCompanyInfo();
    // 获取认证信息
    // this.fetchCertificationInfo();
  },

  methods: {
    // // 获取行业列表
    // fetchIndustries() {
    //   axios.get("http://localhost:8080/Enterprise/industries")
    //       .then(response => {
    //         this.industries = response.data;
    //       })
    //       .catch(error => {
    //         console.error('Error fetching industries:', error);
    //       });
    // },
    // 获取当前公司信息
    fetchCompanyInfo() {
      axios.get("http://localhost:8080/Enterprise/selectAll")
          .then(response => {
            // 假设返回的是单个公司信息
            this.currentCompany = response.data.data.filter(item => item.user_id === this.user.user_id)[0];
            localStorage.setItem('company_id', this.currentCompany.company_id);
          })
          .catch(error => {
            console.error('Error fetching company info:', error);
          });
    },
    // 更新公司信息
    updateEnterpriseInfo() {
      console.log(this.currentCompany)
      axios.put("http://localhost:8080/Enterprise/edit", this.currentCompany)
          .then(response => {
            this.$message.success("更新成功");
          })
          .catch(error => {
            console.error('Error updating company info:', error);
            this.$message.error("更新失败");
          });
    },
    // 获取认证信息
    // fetchCertificationInfo() {
    //   axios.get("http://localhost:8080/Enterprise/certificationInfo")
    //       .then(response => {
    //         this.certificationInfo = response.data;
    //       })
    //       .catch(error => {
    //         console.error('Error fetching certification info:', error);
    //       });
    // },
    // 更新认证信息
    // updateCertificationInfo(row) {
    //   axios.put("http://localhost:8080/Enterprise/editCertification", row)
    //       .then(response => {
    //         this.$message.success("更新成功");
    //         // 更新成功后刷新认证信息列表
    //         this.fetchCertificationInfo();
    //       })
    //       .catch(error => {
    //         console.error('Error updating certification info:', error);
    //         this.$message.error("更新失败");
    //       });
    // },
    // 审核认证信息
    // approveCertificationInfo(row) {
    //   axios.put("http://localhost:8080/Enterprise/approveCertification", row)
    //       .then(response => {
    //         this.$message.success("审核成功");
    //         // 审核成功后刷新认证信息列表
    //         this.fetchCertificationInfo();
    //       })
    //       .catch(error => {
    //         console.error('Error approving certification info:', error);
    //         this.$message.error("审核失败");
    //       });
    // },
//_____________________________________________________________________
    // 获取企业信息
    fetchCompanies() {
      let url = 'http://localhost:8080/Enterprise/selectAll';
      let params = {
        page: this.currentPage,
        size: this.pageSize
      };

      if (this.keyword) {
        axios.get('http://localhost:8080/Enterprise/selectByName', {
          params: {
            company_name: this.keyword
          }
        })
            .then(response => {
              console.log(this.response.data.data)
              this.companies = response.data.data.filter(item => item.user_id === this.user.user_id);
            })
            .catch(error => {
              console.error('Error fetching companies:', error);
            });
      } else {
        axios.get(url, {params})
            .then(response => {
              const data = response.data.data.filter(item => item.user_id === this.user.user_id);
              this.companies = data;
              this.totalItems = data.length;
            })
            .catch(error => {
              console.error('Error fetching companies:', error);
            });
      }
    },
    reset() {
      this.keyword = '';
      this.currentPage = 1;
      this.pageSize = 5;
      this.fetchCompanies();
    },
    handleSelectionChange(val) {
      this.selectedRows = val.map(row => row.company_id);
    },
    showAddDialog() {
      this.isEditing = false;
      this.editItem = {
        company_id: '',
        company_name: '',
        industry: '',
        website: '',
        description: '',
        contact_person: '',
        contact_email: '',
        contact_phone: '',
        address: ''
      };
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
      this.isEditing = false;
    },
    handleSaveEdit() {
      if (this.isEditing) {
        axios.put("http://localhost:8080/Enterprise/edit", this.editItem)
            .then(response => {
              this.$message.success(response.data.message);
              this.closeDialog();
              this.fetchCompanies();
            })
            .catch(error => {
              console.error('Error editing company:', error);
              this.$message.error("编辑失败");
            });
      } else {
        axios.post("http://localhost:8080/Enterprise/add", this.editItem)
            .then(response => {
              this.$message.success(response.data.message);
              this.closeDialog();
              this.fetchCompanies();
            })
            .catch(error => {
              console.error('Error adding new company:', error);
              this.$message.error("新增失败");
            });
      }
    },
    handleEdit(row) {
      this.editItem = Object.assign({}, row);
      this.isEditing = true;
      this.dialogVisible = true;
    },
    handleDelete(company_id) {
      this.$confirm('此操作将永久删除该企业信息，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/Enterprise/delete/${company_id}`)
            .then(response => {
              this.$message.success('删除成功');
              this.fetchCompanies();
            })
            .catch(error => {
              console.error('Error deleting company:', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    delBatch() {
      this.$confirm('此操作将永久删除所选企业信息，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/Enterprise/deleteBatch`, {data: this.selectedRows})
            .then(response => {
              this.$message.success('批量删除成功');
              this.fetchCompanies();
              this.selectedRows = [];
            })
            .catch(error => {
              console.error('Error deleting batch:', error);
              this.$message.error('批量删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消批量删除');
      });
    }
  }
};
</script>

<style scoped>
/* 可以添加一些样式 */
</style>
